import logging
from rest_framework import serializers
from .models import *
from django.utils import timezone
from .utils import *
from .shipping import *
from .serializers_report import ReportSerializer
from .excel_import_handlers import LocalOrderImportHandler, TransferOrderImportHandler, AfterSaleOrderImportHandler
import openpyxl
from datetime import datetime, timedelta

logger = logging.getLogger(__name__)

class BaseOrderSerializer(serializers.ModelSerializer):
    # 订单序列化器基类
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    created_by_username = serializers.SerializerMethodField(read_only=True)
    
    def get_created_by_username(self, obj):
        return obj.created_by.username if obj.created_by else None

class LocalOrderSerializer(BaseOrderSerializer):
    class Meta:
        model = LocalOrder
        exclude = ('created_by',)

    def validate(self, attrs):
        # 如果is_pickup为True，则pickup_time不能为空
        is_pickup = attrs.get('is_pickup', False)
        pickup_time = attrs.get('pickup_time')
        
        if is_pickup and not pickup_time:
            raise serializers.ValidationError({
                'pickup_time': '自提时间不能为空'
            })
        
        return attrs
    
    def process_excel_import(self, file, user):
        return LocalOrderImportHandler.process_excel_import(file, user)
    
    def process_batch_delete(self, fs_no_list):
        if not isinstance(fs_no_list, list): raise ValueError('请提供FS编号列表')

        success_count = 0
        error_records = []

        for fs_no in fs_no_list:
            try:
                local_order = LocalOrder.objects.get(fs_no=fs_no)
                local_order.is_delete = True
                local_order.save()
                success_count += 1
            except LocalOrder.DoesNotExist:
                error_records.append({'fs_no': fs_no, 'error': '未找到该订单'})

        return {'success_count': success_count, 'error_count': len(error_records), 'error_records': error_records}

    def process_batch_update_date(self, fs_no_list, create_time):
        if not isinstance(fs_no_list, list): raise ValueError('请提供FS编号列表')
        if not create_time: raise ValueError('请提供创建时间')
        
        try:
            if isinstance(create_time, str):
                dt = datetime.strptime(create_time, '%Y-%m-%d %H:%M:%S')
                create_time = timezone.make_aware(dt)
        except ValueError:
            raise ValueError('时间格式错误，请使用 YYYY-MM-DD HH:MM:SS 格式')
            
        success_count = 0
        error_records = []
        for fs_no in fs_no_list:
            try:
                local_order = LocalOrder.objects.get(fs_no=fs_no)
                local_order.create_time = create_time
                local_order.save()
                success_count += 1
            except LocalOrder.DoesNotExist:
                error_records.append({'fs_no': fs_no, 'error': '未找到该订单'})

        return {'success_count': success_count, 'error_count': len(error_records), 'error_records': error_records}

class TransferOrderSerializer(BaseOrderSerializer):
    class Meta:
        model = TransferOrder
        exclude = ('created_by',)

    def validate(self, attrs):
        # 如果is_pickup为True，则pickup_time不能为空
        is_pickup = attrs.get('is_pickup', False)
        pickup_time = attrs.get('pickup_time')
        
        if is_pickup and not pickup_time:
            raise serializers.ValidationError({
                'pickup_time': '自提时间不能为空'
            })
        
        return attrs
    
    def process_excel_import(self, file, user):
        return TransferOrderImportHandler.process_excel_import(file, user)
       

    def process_batch_delete(self, cw_no_list):
        if not isinstance(cw_no_list, list): raise ValueError('请提供CW编号列表')

        success_count = 0
        error_records = []

        for cw_no in cw_no_list:
            try:
                transfer_order = TransferOrder.objects.get(cw_no=cw_no)
                transfer_order.is_delete = True
                transfer_order.save()
                success_count += 1
            except TransferOrder.DoesNotExist:
                error_records.append({'cw_no': cw_no, 'error': '未找到该订单'})

        return {'success_count': success_count, 'error_count': len(error_records), 'error_records': error_records}

    def process_batch_update_date(self, cw_no_list, create_time):
        if not isinstance(cw_no_list, list): raise ValueError('请提供CW编号列表')
        if not create_time: raise ValueError('请提供创建时间')
        
        try:
            if isinstance(create_time, str):
                dt = datetime.strptime(create_time, '%Y-%m-%d %H:%M:%S')
                create_time = timezone.make_aware(dt)
        except ValueError:
            raise ValueError('时间格式错误，请使用 YYYY-MM-DD HH:MM:SS 格式')
            
        success_count = 0
        error_records = []
        for cw_no in cw_no_list:
            try:
                transfer_order = TransferOrder.objects.get(cw_no=cw_no)
                transfer_order.create_time = create_time
                transfer_order.save()
                success_count += 1
            except TransferOrder.DoesNotExist:
                error_records.append({'cw_no': cw_no, 'error': '未找到该订单'})

        return {'success_count': success_count, 'error_count': len(error_records), 'error_records': error_records}


class AfterSaleOrderSerializer(BaseOrderSerializer):
    class Meta:
        model = AfterSaleOrder
        exclude = ('created_by',)
    
    def process_excel_import(self, file, user):
        return AfterSaleOrderImportHandler.process_excel_import(file, user)

class RelocationOrderSerializer(BaseOrderSerializer):
    class Meta:
        model = RelocationOrder
        exclude = ('created_by',)

class CrossOrderSerializer(BaseOrderSerializer):
    class Meta:
        model = CrossOrder
        exclude = ('created_by',)

class ReturnOrderSerializer(BaseOrderSerializer):
    class Meta:
        model = ReturnOrder
        exclude = ('created_by',)

class InventoryReceiveOrderSerializer(BaseOrderSerializer):
    class Meta:
        model = InventoryReceiveOrder
        exclude = ('created_by',)

class RepairOrderSerializer(BaseOrderSerializer):
    class Meta:
        model = RepairOrder
        exclude = ('created_by',)

class UnprocessedOrderSerializer(BaseOrderSerializer):
    class Meta:
        model = UnprocessedOrder
        exclude = ('created_by',)
    
    def save_unprocessed_orders_data(self, data, user):
        """保存未处理订单统计数据"""
        if not data or not data.get('statistics_date'):
            raise ValueError('数据或统计日期不能为空')
        
        # 验证必需字段
        required_sections = ['sentBefore16', 'unsentBetween16And17', 'unsentBetween17And18']
        for section in required_sections:
            if section not in data:
                raise ValueError(f'缺少{section}数据')
        
        try:
            statistics_date = data['statistics_date']
            datetime.strptime(statistics_date, '%Y-%m-%d')  # 验证日期格式
            
            # 构建JSON数据
            order_identifier = f"statistics_{statistics_date}"
            json_data = {
                'statistics_date': statistics_date,
                'order_identifier': order_identifier,
                'type': 'statistics',
                'description': f'{statistics_date}未处理订单统计数据',
                'sentBefore16': data.get('sentBefore16', {}),
                'unsentBetween16And17': data.get('unsentBetween16And17', {}),
                'unsentBetween17And18': data.get('unsentBetween17And18', {}),
                'created_at': timezone.now().isoformat(),
                'created_by': user.username if user else None
            }
            
            # 创建或更新记录
            try:
                unprocessed_order = UnprocessedOrder.objects.get(json_data__order_identifier=order_identifier)
                unprocessed_order.json_data = json_data
                unprocessed_order.created_by = user
                unprocessed_order.save()
            except UnprocessedOrder.DoesNotExist:
                unprocessed_order = UnprocessedOrder.objects.create(json_data=json_data, created_by=user)
            
            return {
                'id': unprocessed_order.id,
                'statistics_date': statistics_date,
                'sentBefore16': data.get('sentBefore16', {}),
                'unsentBetween16And17': data.get('unsentBetween16And17', {}),
                'unsentBetween17And18': data.get('unsentBetween17And18', {}),
                'create_time': unprocessed_order.create_time.isoformat(),
                'update_time': unprocessed_order.update_time.isoformat(),
                'created_by': user.username if user else None
            }
            
        except ValueError as e:
            if 'time data' in str(e):
                raise ValueError('统计日期格式无效，请使用YYYY-MM-DD格式')
            raise e
        except Exception as e:
            raise ValueError(f'保存数据失败: {str(e)}')
    
    def get_unprocessed_orders_data(self, start_date, end_date):
        """获取未处理订单数据"""
        if not start_date or not end_date:
            today = datetime.now().strftime('%Y-%m-%d')
            start_date = end_date = today
        
        start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
        end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()
        
        result = {}
        default_data = {
            "localOrder": 0, "transferOrder": 0, "changeCodeOrder": 0,
            "aftersaleOrder": 0, "adjustOrder": 0
        }
        
        current_date = start_date_obj
        while current_date <= end_date_obj:
            date_str = current_date.strftime('%Y-%m-%d')
            order_identifier = f"statistics_{date_str}"
            
            try:
                unprocessed_order = UnprocessedOrder.objects.get(
                    json_data__order_identifier=order_identifier,
                    json_data__type='statistics'
                )
                json_data = unprocessed_order.json_data or {}
                result[date_str] = {
                    "sentBefore16": json_data.get('sentBefore16', default_data),
                    "unsentBetween16And17": json_data.get('unsentBetween16And17', default_data),
                    "unsentBetween17And18": json_data.get('unsentBetween17And18', default_data)
                }
            except UnprocessedOrder.DoesNotExist:
                result[date_str] = {
                    "sentBefore16": default_data,
                    "unsentBetween16And17": default_data,
                    "unsentBetween17And18": default_data
                }
            
            current_date += timedelta(days=1)
        
        return result

class ShippingFeeConfigSerializer(serializers.ModelSerializer):
    # 运费配置序列化器
    carrier_display = serializers.CharField(source='get_carrier_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    
    class Meta:
        model = ShippingFeeConfig
        fields = '__all__'
        
    def validate(self, data):
        if data.get('min_weight', 0) >= data.get('max_weight', 0): raise serializers.ValidationError('最小重量必须小于最大重量')
        if data.get('min_volume', 0) >= data.get('max_volume', 0): raise serializers.ValidationError('最小体积必须小于最大体积')
        if data.get('volume', 0) <= 0: raise serializers.ValidationError('体积必须大于0')
        return data


class OrderQASerializer(BaseOrderSerializer):
    """订单问答序列化器"""
    time_slot_display = serializers.CharField(source='get_time_slot_display', read_only=True)
    
    class Meta:
        model = OrderQA
        exclude = ('created_by',)
    
    def validate_question_no(self, value):
        """验证提问单号格式"""
        if not value.startswith('Q'):
            raise serializers.ValidationError('提问单号必须以Q开头')
        return value
